#include <myheader.h>

/*Usage:  */
int main(int argc, char *argv[])
{
    int pipefd[2];
    pipe(pipefd);
    //0为读端，1为写端
    if(fork()==0){
        const char *data1 = "hello";
        const char *data2 = "text_context";

        //子进程像pipe写
        int ret = close(pipefd[0]);
        ERROR_CHECK(ret,-1,"close_pipefd[0]");
        //防止数据粘包,将要发的数据大小先发过去
        char str_len[3];
        snprintf(str_len,sizeof(str_len),"%02d",(int)strlen(data1));
        ret = write(pipefd[1],str_len,2);
        ERROR_CHECK(ret,-1,"first_write_pipefd[1]_size");
        ret = write(pipefd[1],data1,strlen(data1));
        ERROR_CHECK(ret,-1,"second_write_pipefd[1]");
        

        //发送第二段数据
        memset(str_len,0,sizeof(str_len));
        snprintf(str_len,sizeof(str_len),"%02d",(int)strlen(data2));
        ret = write(pipefd[1],str_len,2);
        ERROR_CHECK(ret,-1,"third_write_pipefd[1]");
        ret = write(pipefd[1],data2,strlen(data2));
        ERROR_CHECK(ret,-1,"fourth_write_pipefd[1]");

        ret = close(pipefd[1]);
        ERROR_CHECK(ret,-1,"close_pipefd[1]");

    }else{
        int ret;
        //接收子进程的数据
        ret = close(pipefd[1]);
        ERROR_CHECK(ret,-1,"close_pipefd[0]");
        


        char buf[60] = {0};
        ret = read(pipefd[0],buf,2);
        ERROR_CHECK(ret,-1,"first_read_pipefd[0]");
        

        //将读取的字符串转换成数字
        int read_size = atoi(buf);
        
        //读取第一段字符串
        memset(buf,0,sizeof(buf));
        int read_real_cnt = read(pipefd[0],buf,read_size);
        ERROR_CHECK(read_real_cnt,-1,"second_read_pipefd[0]");
        //读取到立刻进行行缓冲刷新,打印第一段字符串
        printf("%s\n",buf);
        

        //读取第二段信息
        memset(buf,0,sizeof(buf));
        ret = read(pipefd[0],buf,2);
        ERROR_CHECK(ret,-1,"second_read_pipefd[0]");
        read_size = atoi(buf);
        
        //读取第二段字符串
        memset(buf,0,sizeof(buf));
        read(pipefd[0],buf,read_size);
        ERROR_CHECK(ret,-1,"read_pipefd[0]");
        printf("%s\n",buf);
        close(pipefd[0]);
        //收尸
        wait(NULL);
    }
    return 0;
}

